package com.fyy.netty.chapter01.c1;

import java.nio.ByteBuffer;

/**
 * @Author fyy
 * @Description ByteBuffer粘包半包
 * @Date 2021/4/20 17:35
 */
public class ByteBufferPackage {

    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put("Hello,word\nI am fyy\nHe is".getBytes());
        split(buffer);
        buffer.put("a apply".getBytes());
        split(buffer);
    }

    public static void split(ByteBuffer buffer){
        //切换未读
        buffer.flip();
        for (int i = 0; i < buffer.limit(); i++) {
            if(buffer.get(i) == '\n'){
                int length = i + 1 - buffer.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                //读取
                for (int j = 0; j < length; j++) {
                    target.put(buffer.get());
                }
            }
        }
        //切换写
        buffer.compact(); //不能使用clear
    }

}
